//
//  TestWebViewController.swift
//  ADKit_Example
//
//  Created by Adoma on 2020/10/29.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import ADKit
import WebKit

class TestWebViewController: UIViewController {
    
    var webView: WKWebView!
    
    var handler: ScriptMessageHandler!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .random
        
        let config = WKWebViewConfiguration()
        
        makeHandler()
        
        config.userContentController.add(handler: handler)

        webView = WKWebView.init(frame: .zero, configuration: config)
        view.addSubview(webView)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        if let path = Bundle.main.path(forResource: "testWeb", ofType: ".html") {
            webView.load(.init(url: .init(fileURLWithPath: path)))
        }
    }
    
    func makeHandler() {
        
        let phone = MessageHandler.init(name: "phone") { (body) in
            UIApplication.shared.open(URL.init(string: "tel://\(body.stringValue)")!)
        }
        
        handler = .init(handlers: [phone])
    }
    
    deinit {
        handler?.removeFromController()
        print("TestWebViewController deinit")
    }

}
